3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 namespace Wikimedia\Rdbms
;
38 class DatabaseSqlite
extends Database
{
39 /** @var string|null Directory for SQLite database files listed under their DB name */
41 /** @var string|null Explicit path for the SQLite database file */
43 /** @var string Transaction mode */
46 /** @var int The number of rows affected as an integer */
47 protected $lastAffectedRowCount;
49 protected $lastResultHandle;
54 /** @var FSLockManager (hopefully on the same server as the DB) */
57 /** @var array List of shared database already attached to this connection */
58 private $alreadyAttached = [];
60 /** @var bool Whether full text is enabled */
61 private static $fulltextEnabled = null;
64 * Additional params include:
65 * - dbDirectory : directory containing the DB and the lock file directory
66 * - dbFilePath : use this to force the path of the DB file
67 * - trxMode : one of (deferred, immediate, exclusive)
70 public function __construct( array $p ) {
71 if ( isset( $p['dbFilePath'] ) ) {
72 $this->dbPath
= $p['dbFilePath'];
73 if ( !strlen( $p['dbname'] ) ) {
74 $p['dbname'] = self
::generateDatabaseName( $this->dbPath
);
76 } elseif ( isset( $p['dbDirectory'] ) ) {
77 $this->dbDir
= $p['dbDirectory'];
80 // Set a dummy user to make initConnection() trigger open()
81 parent
::__construct( [ 'user' => '@' ] +
$p );
83 $this->trxMode
= strtoupper( $p['trxMode'] ??
'' );
85 $lockDirectory = $this->getLockFileDirectory();
86 if ( $lockDirectory !== null ) {
87 $this->lockMgr
= new FSLockManager( [
88 'domain' => $this->getDomainID(),
89 'lockDirectory' => $lockDirectory
92 $this->lockMgr
= new NullLockManager( [ 'domain' => $this->getDomainID() ] );
96 protected static function getAttributes() {
97 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
101 * @param string $filename
102 * @param array $p Options map; supports:
103 * - flags : (same as __construct counterpart)
104 * - trxMode : (same as __construct counterpart)
105 * - dbDirectory : (same as __construct counterpart)
106 * @return DatabaseSqlite
109 public static function newStandaloneInstance( $filename, array $p = [] ) {
110 $p['dbFilePath'] = $filename;
112 $p['tablePrefix'] = '';
113 /** @var DatabaseSqlite $db */
114 $db = Database
::factory( 'sqlite', $p );
122 public function getType() {
127 * @todo Check if it should be true like parent class
131 public function implicitGroupby() {
135 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
138 // Note that for SQLite, $server, $user, and $pass are ignored
140 if ( $schema !== null ) {
141 throw new DBExpectedError( $this, __CLASS__
. ": cannot use schemas ('$schema')" );
144 if ( $this->dbPath
!== null ) {
145 $path = $this->dbPath
;
146 } elseif ( $this->dbDir
!== null ) {
147 $path = self
::generateFileName( $this->dbDir
, $dbName );
149 throw new DBExpectedError( $this, __CLASS__
. ": DB path or directory required" );
152 if ( !in_array( $this->trxMode
, [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ], true ) ) {
153 throw new DBExpectedError(
155 __CLASS__
. ": invalid transaction mode '{$this->trxMode}'"
159 if ( !self
::isProcessMemoryPath( $path ) && !is_readable( $path ) ) {
160 $error = "SQLite database file not readable";
161 $this->connLogger
->error(
162 "Error connecting to {db_server}: {error}",
163 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
165 throw new DBConnectionError( $this, $error );
173 [ PDO
::ATTR_PERSISTENT
=> (bool)( $this->flags
& self
::DBO_PERSISTENT
) ]
175 // Set error codes only, don't raise exceptions
176 $conn->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
177 } catch ( PDOException
$e ) {
178 $error = $e->getMessage();
179 $this->connLogger
->error(
180 "Error connecting to {db_server}: {error}",
181 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
183 throw new DBConnectionError( $this, $error );
187 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
190 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
191 // Enforce LIKE to be case sensitive, just like MySQL
192 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
193 // Apply an optimizations or requirements regarding fsync() usage
194 $sync = $this->connectionVariables
['synchronous'] ??
null;
195 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
196 $this->query( "PRAGMA synchronous = $sync", __METHOD__
, $flags );
198 } catch ( Exception
$e ) {
199 // Connection was not fully initialized and is not safe for use
206 * @return string|null SQLite DB file path
207 * @throws DBUnexpectedError
210 public function getDbFilePath() {
211 return $this->dbPath ?? self
::generateFileName( $this->dbDir
, $this->getDBname() );
215 * @return string|null Lock file directory
217 public function getLockFileDirectory() {
218 if ( $this->dbPath
!== null && !self
::isProcessMemoryPath( $this->dbPath
) ) {
219 return dirname( $this->dbPath
) . '/locks';
220 } elseif ( $this->dbDir
!== null && !self
::isProcessMemoryPath( $this->dbDir
) ) {
221 return $this->dbDir
. '/locks';
228 * Does not actually close the connection, just destroys the reference for GC to do its work
231 protected function closeConnection() {
238 * Generates a database file name. Explicitly public for installer.
239 * @param string $dir Directory where database resides
240 * @param string|bool $dbName Database name (or false from Database::factory, validated here)
242 * @throws DBUnexpectedError
244 public static function generateFileName( $dir, $dbName ) {
246 throw new DBUnexpectedError( null, __CLASS__
. ": no DB directory specified" );
247 } elseif ( self
::isProcessMemoryPath( $dir ) ) {
248 throw new DBUnexpectedError(
250 __CLASS__
. ": cannot use process memory directory '$dir'"
252 } elseif ( !strlen( $dbName ) ) {
253 throw new DBUnexpectedError( null, __CLASS__
. ": no DB name specified" );
256 return "$dir/$dbName.sqlite";
260 * @param string $path
263 private static function generateDatabaseName( $path ) {
264 if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
265 // E.g. "file::memory:?cache=shared" => ":memory":
267 } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
268 // E.g. "file:memdb1?mode=memory" => ":memdb1:"
271 // E.g. "/home/.../some_db.sqlite3" => "some_db"
272 return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
277 * @param string $path
280 private static function isProcessMemoryPath( $path ) {
281 return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
285 * Check if the searchindext table is FTS enabled.
286 * @return bool False if not enabled.
288 public function checkForEnabledSearch() {
289 if ( self
::$fulltextEnabled === null ) {
290 self
::$fulltextEnabled = false;
291 $table = $this->tableName( 'searchindex' );
293 "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'",
295 self
::QUERY_IGNORE_DBO_TRX
298 $row = $res->fetchRow();
299 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
303 return self
::$fulltextEnabled;
307 * Returns version of currently supported SQLite fulltext search module or false if none present.
310 static function getFulltextSearchModule() {
311 static $cachedResult = null;
312 if ( $cachedResult !== null ) {
313 return $cachedResult;
315 $cachedResult = false;
316 $table = 'dummy_search_test';
318 $db = self
::newStandaloneInstance( ':memory:' );
319 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
320 $cachedResult = 'FTS3';
324 return $cachedResult;
328 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
331 * @param string $name Database name to be used in queries like
332 * SELECT foo FROM dbname.table
333 * @param bool|string $file Database file name. If omitted, will be generated
334 * using $name and configured data directory
335 * @param string $fname Calling function name
336 * @return IResultWrapper
338 public function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
339 $file = is_string( $file ) ?
$file : self
::generateFileName( $this->dbDir
, $name );
340 $encFile = $this->addQuotes( $file );
343 "ATTACH DATABASE $encFile AS $name",
345 self
::QUERY_IGNORE_DBO_TRX
349 protected function isWriteQuery( $sql ) {
350 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
353 protected function isTransactableQuery( $sql ) {
354 return parent
::isTransactableQuery( $sql ) && !in_array(
355 $this->getQueryVerb( $sql ),
356 [ 'ATTACH', 'PRAGMA' ],
362 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
365 * @return bool|IResultWrapper
367 protected function doQuery( $sql ) {
368 $res = $this->getBindingHandle()->query( $sql );
369 if ( $res === false ) {
373 $resource = ResultWrapper
::unwrap( $res );
374 $this->lastAffectedRowCount
= $resource->rowCount();
375 $res = new ResultWrapper( $this, $resource->fetchAll() );
381 * @param IResultWrapper|mixed $res
383 function freeResult( $res ) {
384 if ( $res instanceof ResultWrapper
) {
390 * @param IResultWrapper|array $res
391 * @return stdClass|bool
393 function fetchObject( $res ) {
394 $resource =& ResultWrapper
::unwrap( $res );
396 $cur = current( $resource );
397 if ( is_array( $cur ) ) {
400 foreach ( $cur as $k => $v ) {
401 if ( !is_numeric( $k ) ) {
413 * @param IResultWrapper|mixed $res
416 function fetchRow( $res ) {
417 $resource =& ResultWrapper
::unwrap( $res );
418 $cur = current( $resource );
419 if ( is_array( $cur ) ) {
429 * The PDO::Statement class implements the array interface so count() will work
431 * @param IResultWrapper|array|false $res
434 function numRows( $res ) {
435 // false does not implement Countable
436 $resource = ResultWrapper
::unwrap( $res );
438 return is_array( $resource ) ?
count( $resource ) : 0;
442 * @param IResultWrapper $res
445 function numFields( $res ) {
446 $resource = ResultWrapper
::unwrap( $res );
447 if ( is_array( $resource ) && count( $resource ) > 0 ) {
448 // The size of the result array is twice the number of fields. (T67578)
449 return count( $resource[0] ) / 2;
451 // If the result is empty return 0
457 * @param IResultWrapper $res
461 function fieldName( $res, $n ) {
462 $resource = ResultWrapper
::unwrap( $res );
463 if ( is_array( $resource ) ) {
464 $keys = array_keys( $resource[0] );
473 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
475 * @param string $name
476 * @param string $format
479 function tableName( $name, $format = 'quoted' ) {
480 // table names starting with sqlite_ are reserved
481 if ( strpos( $name, 'sqlite_' ) === 0 ) {
485 return str_replace( '"', '', parent
::tableName( $name, $format ) );
489 * This must be called after nextSequenceVal
493 function insertId() {
494 // PDO::lastInsertId yields a string :(
495 return intval( $this->getBindingHandle()->lastInsertId() );
499 * @param IResultWrapper|array $res
502 function dataSeek( $res, $row ) {
503 $resource =& ResultWrapper
::unwrap( $res );
506 for ( $i = 0; $i < $row; $i++
) {
515 function lastError() {
516 if ( !is_object( $this->conn
) ) {
517 return "Cannot return last error, no db connection";
519 $e = $this->conn
->errorInfo();
527 function lastErrno() {
528 if ( !is_object( $this->conn
) ) {
529 return "Cannot return last error, no db connection";
531 $info = $this->conn
->errorInfo();
540 protected function fetchAffectedRowCount() {
541 return $this->lastAffectedRowCount
;
544 function tableExists( $table, $fname = __METHOD__
) {
545 $tableRaw = $this->tableName( $table, 'raw' );
546 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
547 return true; // already known to exist
550 $encTable = $this->addQuotes( $tableRaw );
552 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
554 self
::QUERY_IGNORE_DBO_TRX
557 return $res->numRows() ?
true : false;
561 * Returns information about an index
562 * Returns false if the index does not exist
563 * - if errors are explicitly ignored, returns NULL on failure
565 * @param string $table
566 * @param string $index
567 * @param string $fname
568 * @return array|false
570 function indexInfo( $table, $index, $fname = __METHOD__
) {
571 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
572 $res = $this->query( $sql, $fname, self
::QUERY_IGNORE_DBO_TRX
);
573 if ( !$res ||
$res->numRows() == 0 ) {
577 foreach ( $res as $row ) {
578 $info[] = $row->name
;
585 * @param string $table
586 * @param string $index
587 * @param string $fname
590 function indexUnique( $table, $index, $fname = __METHOD__
) {
591 $row = $this->selectRow( 'sqlite_master', '*',
594 'name' => $this->indexName( $index ),
596 if ( !$row ||
!isset( $row->sql
) ) {
600 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
601 $indexPos = strpos( $row->sql
, 'INDEX' );
602 if ( $indexPos === false ) {
605 $firstPart = substr( $row->sql
, 0, $indexPos );
606 $options = explode( ' ', $firstPart );
608 return in_array( 'UNIQUE', $options );
612 * Filter the options used in SELECT statements
614 * @param array $options
617 function makeSelectOptions( $options ) {
618 foreach ( $options as $k => $v ) {
619 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
624 return parent
::makeSelectOptions( $options );
628 * @param array $options
631 protected function makeUpdateOptionsArray( $options ) {
632 $options = parent
::makeUpdateOptionsArray( $options );
633 $options = self
::fixIgnore( $options );
639 * @param array $options
642 static function fixIgnore( $options ) {
643 # SQLite uses OR IGNORE not just IGNORE
644 foreach ( $options as $k => $v ) {
645 if ( $v == 'IGNORE' ) {
646 $options[$k] = 'OR IGNORE';
654 * @param array $options
657 function makeInsertOptions( $options ) {
658 $options = self
::fixIgnore( $options );
660 return parent
::makeInsertOptions( $options );
664 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
665 * @param string $table
667 * @param string $fname
668 * @param array $options
671 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
672 if ( !count( $a ) ) {
676 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
677 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
678 $affectedRowCount = 0;
680 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
681 foreach ( $a as $v ) {
682 parent
::insert( $table, $v, "$fname/multi-row", $options );
683 $affectedRowCount +
= $this->affectedRows();
685 $this->endAtomic( $fname );
686 } catch ( Exception
$e ) {
687 $this->cancelAtomic( $fname );
690 $this->affectedRowCount
= $affectedRowCount;
692 parent
::insert( $table, $a, "$fname/single-row", $options );
699 * @param string $table
700 * @param array $uniqueIndexes Unused
701 * @param string|array $rows
702 * @param string $fname
704 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
705 if ( !count( $rows ) ) {
709 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
710 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
711 $affectedRowCount = 0;
713 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
714 foreach ( $rows as $v ) {
715 $this->nativeReplace( $table, $v, "$fname/multi-row" );
716 $affectedRowCount +
= $this->affectedRows();
718 $this->endAtomic( $fname );
719 } catch ( Exception
$e ) {
720 $this->cancelAtomic( $fname );
723 $this->affectedRowCount
= $affectedRowCount;
725 $this->nativeReplace( $table, $rows, "$fname/single-row" );
730 * Returns the size of a text field, or -1 for "unlimited"
731 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
733 * @param string $table
734 * @param string $field
737 function textFieldSize( $table, $field ) {
744 function unionSupportsOrderAndLimit() {
749 * @param string[] $sqls
750 * @param bool $all Whether to "UNION ALL" or not
753 function unionQueries( $sqls, $all ) {
754 $glue = $all ?
' UNION ALL ' : ' UNION ';
756 return implode( $glue, $sqls );
762 function wasDeadlock() {
763 return $this->lastErrno() == 5; // SQLITE_BUSY
769 function wasReadOnlyError() {
770 return $this->lastErrno() == 8; // SQLITE_READONLY;
773 public function wasConnectionError( $errno ) {
774 return $errno == 17; // SQLITE_SCHEMA;
777 protected function wasKnownStatementRollbackError() {
778 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
779 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
780 // https://sqlite.org/lang_createtable.html#uniqueconst
781 // https://sqlite.org/lang_conflict.html
785 public function serverIsReadOnly() {
786 $path = $this->getDbFilePath();
788 return ( !self
::isProcessMemoryPath( $path ) && !is_writable( $path ) );
792 * @return string Wikitext of a link to the server software's web site
794 public function getSoftwareLink() {
795 return "[{{int:version-db-sqlite-url}} SQLite]";
799 * @return string Version information from the database
801 function getServerVersion() {
802 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
808 * Get information about a given field
809 * Returns false if the field does not exist.
811 * @param string $table
812 * @param string $field
813 * @return SQLiteField|bool False on failure
815 function fieldInfo( $table, $field ) {
816 $tableName = $this->tableName( $table );
817 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
818 $res = $this->query( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
819 foreach ( $res as $row ) {
820 if ( $row->name
== $field ) {
821 return new SQLiteField( $row, $tableName );
828 protected function doBegin( $fname = '' ) {
829 if ( $this->trxMode
!= '' ) {
830 $this->query( "BEGIN {$this->trxMode}", $fname );
832 $this->query( 'BEGIN', $fname );
840 function strencode( $s ) {
841 return substr( $this->addQuotes( $s ), 1, -1 );
848 function encodeBlob( $b ) {
849 return new Blob( $b );
853 * @param Blob|string $b
856 function decodeBlob( $b ) {
857 if ( $b instanceof Blob
) {
865 * @param string|int|null|bool|Blob $s
868 function addQuotes( $s ) {
869 if ( $s instanceof Blob
) {
870 return "x'" . bin2hex( $s->fetch() ) . "'";
871 } elseif ( is_bool( $s ) ) {
873 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
874 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
875 // This is a known limitation of SQLite's mprintf function which PDO
876 // should work around, but doesn't. I have reported this to php.net as bug #63419:
877 // https://bugs.php.net/bug.php?id=63419
878 // There was already a similar report for SQLite3::escapeString, bug #62361:
879 // https://bugs.php.net/bug.php?id=62361
880 // There is an additional bug regarding sorting this data after insert
881 // on older versions of sqlite shipped with ubuntu 12.04
882 // https://phabricator.wikimedia.org/T74367
883 $this->queryLogger
->debug(
885 ': Quoting value containing null byte. ' .
886 'For consistency all binary data should have been ' .
887 'first processed with self::encodeBlob()'
889 return "x'" . bin2hex( (string)$s ) . "'";
891 return $this->getBindingHandle()->quote( (string)$s );
895 public function buildSubstring( $input, $startPosition, $length = null ) {
896 $this->assertBuildSubstringParams( $startPosition, $length );
897 $params = [ $input, $startPosition ];
898 if ( $length !== null ) {
901 return 'SUBSTR(' . implode( ',', $params ) . ')';
905 * @param string $field Field or column to cast
909 public function buildStringCast( $field ) {
910 return 'CAST ( ' . $field . ' AS TEXT )';
914 * No-op version of deadlockLoop
918 public function deadlockLoop( /*...*/ ) {
919 $args = func_get_args();
920 $function = array_shift( $args );
922 return $function( ...$args );
929 protected function replaceVars( $s ) {
930 $s = parent
::replaceVars( $s );
931 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
932 // CREATE TABLE hacks to allow schema file sharing with MySQL
934 // binary/varbinary column type -> blob
935 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
936 // no such thing as unsigned
937 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
939 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
940 // floating point types -> REAL
942 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
947 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
948 // TEXT normalization
949 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
950 // BLOB normalization
951 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
953 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
955 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
957 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
958 // binary collation type -> nothing
959 $s = preg_replace( '/\bbinary\b/i', '', $s );
960 // auto_increment -> autoincrement
961 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
962 // No explicit options
963 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
964 // AUTOINCREMENT should immedidately follow PRIMARY KEY
965 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
966 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
967 // No truncated indexes
968 $s = preg_replace( '/\(\d+\)/', '', $s );
970 $s = preg_replace( '/\bfulltext\b/i', '', $s );
971 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
972 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
973 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
974 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
975 // INSERT IGNORE --> INSERT OR IGNORE
976 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
982 public function lock( $lockName, $method, $timeout = 5 ) {
983 $status = $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout );
985 $this->lockMgr
instanceof FSLockManager
&&
986 $status->hasMessage( 'lockmanager-fail-openlock' )
988 throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
991 return $status->isOK();
994 public function unlock( $lockName, $method ) {
995 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
999 * Build a concatenation list to feed into a SQL query
1001 * @param string[] $stringList
1004 function buildConcat( $stringList ) {
1005 return '(' . implode( ') || (', $stringList ) . ')';
1008 public function buildGroupConcatField(
1009 $delim, $table, $field, $conds = '', $join_conds = []
1011 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1013 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1017 * @param string $oldName
1018 * @param string $newName
1019 * @param bool $temporary
1020 * @param string $fname
1021 * @return bool|IResultWrapper
1022 * @throws RuntimeException
1024 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1025 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1026 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1027 $obj = $this->fetchObject( $res );
1029 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1032 $sql = preg_replace(
1034 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1036 $this->addIdentifierQuotes( $newName ),
1041 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1042 $this->queryLogger
->debug(
1043 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1045 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1049 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1051 // Take over indexes
1052 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1053 foreach ( $indexList as $index ) {
1054 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1058 if ( $index->unique
) {
1059 $sql = 'CREATE UNIQUE INDEX';
1061 $sql = 'CREATE INDEX';
1063 // Try to come up with a new index name, given indexes have database scope in SQLite
1064 $indexName = $newName . '_' . $index->name
;
1065 $sql .= ' ' . $indexName . ' ON ' . $newName;
1067 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1069 foreach ( $indexInfo as $indexInfoRow ) {
1070 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1073 $sql .= '(' . implode( ',', $fields ) . ')';
1075 $this->query( $sql );
1082 * List all tables on the database
1084 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1085 * @param string $fname Calling function name
1089 function listTables( $prefix = null, $fname = __METHOD__
) {
1090 $result = $this->select(
1098 foreach ( $result as $table ) {
1099 $vars = get_object_vars( $table );
1100 $table = array_pop( $vars );
1102 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1103 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1104 $endArray[] = $table;
1113 * Override due to no CASCADE support
1115 * @param string $tableName
1116 * @param string $fName
1117 * @return bool|IResultWrapper
1118 * @throws DBReadOnlyError
1120 public function dropTable( $tableName, $fName = __METHOD__
) {
1121 if ( !$this->tableExists( $tableName, $fName ) ) {
1124 $sql = "DROP TABLE " . $this->tableName( $tableName );
1126 return $this->query( $sql, $fName, self
::QUERY_IGNORE_DBO_TRX
);
1129 public function setTableAliases( array $aliases ) {
1130 parent
::setTableAliases( $aliases );
1131 foreach ( $this->tableAliases
as $params ) {
1132 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1135 $this->attachDatabase( $params['dbname'] );
1136 $this->alreadyAttached
[$params['dbname']] = true;
1140 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1141 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1142 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1144 "DELETE FROM $encTable WHERE name = $encName",
1146 self
::QUERY_IGNORE_DBO_TRX
1150 public function databasesAreIndependent() {
1157 protected function getBindingHandle() {
1158 return parent
::getBindingHandle();
1163 * @deprecated since 1.29
1165 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );